/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bs.coregamelibrary.session;

import com.bs.coregamelibrary.protocoltea.codec.Message;
import io.netty.channel.Channel;
import java.io.IOException;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * @author dungpt
 */
public abstract class Session implements Serializable {

    private final String id;
    private final Channel channel;

    public Session(String id, Channel channel) throws Exception {
        if (id == null || id.trim().isEmpty() || channel == null) {
            throw new Exception("dkm new session dang hoang!");
        } else {
            this.id = id;
            this.channel = channel;
        }
    }

    /**
     * @return the id
     */
    protected String getId() {
        return id;
    }

    /**
     * @return the status
     */
    public abstract AtomicInteger getStatus();

    /**
     * @param status the status to set
     */
    public abstract void setStatus(AtomicInteger status);

    /**
     * @return the token
     */
    public abstract String getToken();

    /**
     * @param token the token to set
     */
    public abstract void setToken(String token);

    /**
     * @return the channel
     */
    protected Channel getChannel() {
        return channel;
    }

    protected boolean sendMessage(Object message) throws IOException {
        boolean result = false;
        if (message != null) {
            if (message instanceof Message) {
                Message msg = (Message) message;
                channel.writeAndFlush(msg.toByteBuf());
                result = true;
            } else {
                channel.writeAndFlush(message);
                result = true;
            }
        }
        return result;
    }
}
